//
import { ModifyArrayState } from "common/history";
import * as mvc from "common/mvc";
import * as dec from "common/decorator";
//
import * as dbtps from "../types";
import { Item } from "./item";
import { Armature, Display } from "./dragonBones";
/**
 * 库。
 */
export default class Library extends mvc.Model {
    public static toString(): string {
        return "[class dragonBones.model.Library]";
    }
    /**
     * 库项目。
     */
    @dec.getterSetter(true, false)
    public items: Item[] = [];
    /**
     * 选中项目。
     */
    @dec.getterSetter(true, false)
    public selection: Item[] = [];

    private _createArmatureCount: number = 1;
    /**
     * 添加项目。
     */
    public addItem(item: Item): void {
        console.assert(this.items.indexOf(item) < 0);

        ModifyArrayState.createState(
            this.items,
            this.items.length,
            item,
            { type: dbtps.MNotificationType.LibraryAddItem, target: this, data: item }
        );
    }
    /**
     * 删除项目。
     */
    public removeItem(item: Item): void {
        // 取消选中项，清除所有其他项目对该项目的引用，删除（引用保留在历史记录内）
        // const index = this.items.indexOf(item);
        // console.assert(index >= 0);

        // if (item.selected) {
        //     item.selected = false;
        // }

        // this.items.splice(index, 1);
        // this._sendNotification(mvc.MNotificationType.LibraryRemoveItem, item);
    }
    /**
     * 创建骨架。
     */
    public createArmature(): Armature {
        const armature = Armature.create(Armature);
        let armatureName = "";
        do {
            armatureName = `${dbtps.defaultArmatureName}_${this._createArmatureCount++}`;
        }
        while (this.getItem(armatureName));

        dec.history.locked = true;
        armature.name = armatureName;
        dec.history.locked = false;

        this.addItem(armature);

        return armature;
    }
    /**
     * 获取指定项目。（全局名称）
     */
    public getItem(name: string): Item | null {
        for (const item of this.items) {
            if (item.name === name) {
                return item;
            }
        }

        return null;
    }
}